using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using System.Diagnostics;
using MobileClient.UIProcessService;

namespace MobileClient
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class frmMain : System.Windows.Forms.Form
	{

        private MobileClient.UIProcessService.Form m_objForm;
		private frmEntries dlgEntries;
		private MobileClient.ctlButtonMenu m_objFormsMenu;
		private MobileClient.ctlButtonMenu m_objCompletedFormsMenu;
		private System.Windows.Forms.TabControl tabControl1;
		private System.Windows.Forms.TabPage tabForms;
		private System.Windows.Forms.TabPage tabCompleted;
		private string[] m_arrForms;
		private string[] m_arrCompletedForms;

		public frmMain()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			// create the entry dialog
			dlgEntries = new frmEntries();
			// create the Forms menu
			m_objFormsMenu = new MobileClient.ctlButtonMenu();
			m_objFormsMenu.Location = new System.Drawing.Point(4, 4);
			m_objFormsMenu.Size = new System.Drawing.Size(232, 300);
			m_objFormsMenu.OptionClicked += new System.EventHandler(this.m_objFormsMenu_Clicked);
			m_objFormsMenu.ViewClicked += new EventHandler(m_objFormsMenu_ViewClicked);
			m_objFormsMenu.DeleteClicked += new EventHandler(m_objFormsMenu_DeleteClicked);
			this.tabForms.Controls.Add(m_objFormsMenu);
			// create the Forms menu
			m_objCompletedFormsMenu = new MobileClient.ctlButtonMenu();
			m_objCompletedFormsMenu.Location = new System.Drawing.Point(4, 4);
			m_objCompletedFormsMenu.Size = new System.Drawing.Size(232, 300);
			m_objCompletedFormsMenu.OptionClicked += new System.EventHandler(this.m_objCompletedFormsMenu_Clicked);
			m_objCompletedFormsMenu.ViewClicked += new EventHandler(m_objCompletedFormsMenu_ViewClicked);
			m_objCompletedFormsMenu.DeleteClicked += new EventHandler(m_objCompletedFormsMenu_DeleteClicked);
			this.tabCompleted.Controls.Add(m_objCompletedFormsMenu);
		}
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			base.Dispose( disposing );
		}
		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.tabControl1 = new System.Windows.Forms.TabControl();
            this.tabForms = new System.Windows.Forms.TabPage();
            this.tabCompleted = new System.Windows.Forms.TabPage();
            this.tabControl1.SuspendLayout();
            this.SuspendLayout();
            // 
            // tabControl1
            // 
            this.tabControl1.Controls.Add(this.tabForms);
            this.tabControl1.Controls.Add(this.tabCompleted);
            this.tabControl1.Location = new System.Drawing.Point(0, 0);
            this.tabControl1.Name = "tabControl1";
            this.tabControl1.SelectedIndex = 0;
            this.tabControl1.Size = new System.Drawing.Size(238, 272);
            this.tabControl1.TabIndex = 0;
            // 
            // tabForms
            // 
            this.tabForms.Location = new System.Drawing.Point(0, 0);
            this.tabForms.Name = "tabForms";
            this.tabForms.Size = new System.Drawing.Size(238, 249);
            this.tabForms.Text = "Forms";
            // 
            // tabCompleted
            // 
            this.tabCompleted.Location = new System.Drawing.Point(0, 0);
            this.tabCompleted.Name = "tabCompleted";
            this.tabCompleted.Size = new System.Drawing.Size(232, 246);
            this.tabCompleted.Text = "Completed";
            // 
            // frmMain
            // 
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
            this.ClientSize = new System.Drawing.Size(238, 295);
            this.Controls.Add(this.tabControl1);
            this.Name = "frmMain";
            this.Text = "Forms Anywhere";
            this.Load += new System.EventHandler(this.frmMain_Load);
            this.tabControl1.ResumeLayout(false);
            this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>

		private void frmMain_Load(object sender, System.EventArgs e)
		{
			frmSplashScreen dlgSplash = new frmSplashScreen();
			dlgSplash.ShowDialog();
			LoadForms();
			LoadCompletedForms();
		}

		private string[] FindForms()
		{
			string strPath = SettingValues.GetTemplatePath();
			string[] strFiles = Directory.GetFiles(strPath, "*.xml");
			return strFiles;
		}

		private void LoadForms()
		{
			clsButtonMenuItem objItem;

			Cursor.Current = Cursors.WaitCursor;

			m_arrForms = FindForms();

			ArrayList objOptions = new ArrayList();

			foreach(String strFile in m_arrForms)
			{
				objItem = new clsButtonMenuItem(); 
				objItem.Name = Path.GetFileNameWithoutExtension(strFile);
				objItem.Type = clsButtonMenuItem.ItemType.Template;
				objOptions.Add(objItem);
			}

			// create the configuration menu button
			objItem = new clsButtonMenuItem(); 
			objItem.Name = "Configure";
			objItem.Type = clsButtonMenuItem.ItemType.Configuration;
			objOptions.Add(objItem);
			// create the download button
			objItem = new clsButtonMenuItem(); 
			objItem.Name = "Download Templates";
			objItem.Type = clsButtonMenuItem.ItemType.Download;
			objOptions.Add(objItem);
			// replace the menu options
			m_objFormsMenu.Options = objOptions;
			m_objFormsMenu.InitDisplay();

			Cursor.Current = Cursors.Default;
		}

		private string[] FindCompletedForms()
		{
			string strPath = SettingValues.GetResponsePath();
			string[] strFiles = Directory.GetFiles(strPath, "*.xml");
			return strFiles;
		}

		private void LoadCompletedForms()
		{
			clsButtonMenuItem objItem;

			Cursor.Current = Cursors.WaitCursor;

			m_arrCompletedForms = FindCompletedForms();

			ArrayList objOptions = new ArrayList();

			foreach(String strFile in m_arrCompletedForms)
			{
				objItem = new clsButtonMenuItem(); 
				objItem.Name = Path.GetFileNameWithoutExtension(strFile);
				objItem.Type = clsButtonMenuItem.ItemType.Template;
				objOptions.Add(objItem);
			}

			// create the configuration menu button
			objItem = new clsButtonMenuItem(); 
			objItem.Name = "Configure";
			objItem.Type = clsButtonMenuItem.ItemType.Configuration;
			objOptions.Add(objItem);
			// create the upload button
			objItem = new clsButtonMenuItem(); 
			objItem.Name = "Upload Responses";
			objItem.Type = clsButtonMenuItem.ItemType.Upload;
			objOptions.Add(objItem);
			// replace the menu options
			m_objCompletedFormsMenu.Options = objOptions;
			m_objCompletedFormsMenu.InitDisplay();

			Cursor.Current = Cursors.Default;
		}

		private void m_objFormsMenu_Clicked(object sender, System.EventArgs e)
		{
			FillOutForm();
		}

		private void FillOutForm()
		{
			string strSelection = m_objFormsMenu.SelectedOption;
			string strTemplate = String.Empty;
			string strFormName = String.Empty;
			StringBuilder strFileName;

			switch(strSelection)
			{
				case "Configure":
					Options();
					break;
				case "Download Templates":
					DownloadTemplates();
					break;
				case "Upload Responses":
					UploadResponses();
					break;
			}

			// walk through the template array and find the selected item
			for(int nIndex = 0; nIndex < m_arrForms.Length; nIndex++)
			{
				strTemplate = m_arrForms[nIndex];
				strFormName = Path.GetFileNameWithoutExtension(strTemplate);
				if(strFormName == strSelection)
				{
					break;
				}
				else
				{
					strTemplate = String.Empty;
					strFormName = String.Empty;
				}
			}

			if(!String.IsNullOrEmpty(strTemplate))
			{
				try
				{
                    m_objForm = LoadFormTemplate(strTemplate);
					m_objForm.GivenBy = SettingValues.GetUserId();
                    while (m_objForm != null)
                    {
                        dlgEntries.theForm = m_objForm;
                        if (dlgEntries.ShowDialog() == DialogResult.OK)
                        {
                            if (m_objForm.ReadOnly == false)
                            {
                                strFileName = new StringBuilder();
                                strFileName.Append(SettingValues.GetResponsePath());
                                strFileName.Append("\\");
                                strFileName.Append(strFormName);
                                strFileName.Append("_");
                                strFileName.Append(SettingValues.GetUserId());
                                strFileName.Append("_");
                                strFileName.Append(DateTime.Now.Year.ToString("0000"));
                                strFileName.Append(DateTime.Now.Month.ToString("00"));
                                strFileName.Append(DateTime.Now.Day.ToString("00"));
                                strFileName.Append("_");
                                strFileName.Append(DateTime.Now.Hour.ToString("00"));
                                strFileName.Append(DateTime.Now.Minute.ToString("00"));
                                strFileName.Append(".xml");
                                m_objForm = dlgEntries.theForm;
                                SaveFormResponse(m_objForm, strFileName.ToString());
                            }
                        }
                        else
                        {
                            m_objForm = null;
                        }
                    }

                    LoadCompletedForms();
                }
				catch(Exception ex)
				{
					MessageBox.Show(ex.Message);
				}
			}
		}

		private void m_objCompletedFormsMenu_Clicked(object sender, System.EventArgs e)
		{
			ReviewCompletedForm();
		}

		private void ReviewCompletedForm()
		{
			string strSelection = m_objCompletedFormsMenu.SelectedOption;
			string strTemplate = String.Empty;
			string strFormName = String.Empty;

			switch(strSelection)
			{
				case "Configure":
					Options();
					break;
				case "Download Templates":
					DownloadTemplates();
					break;
				case "Upload Responses":
					UploadResponses();
					break;
			}

			// walk through the template array and find the selected item
			for(int nIndex = 0; nIndex < m_arrCompletedForms.Length; nIndex++)
			{
				strTemplate = m_arrCompletedForms[nIndex];
				strFormName = Path.GetFileNameWithoutExtension(strTemplate);
				if(strFormName == strSelection)
				{
					break;
				}
				else
				{
					strTemplate = String.Empty;
					strFormName = String.Empty;
				}
			}

			if(strTemplate != String.Empty)
			{
				try
				{
                    m_objForm = LoadFormTemplate(strTemplate);
					m_objForm.GivenBy = SettingValues.GetUserId();
					dlgEntries.theForm = m_objForm;
					if(dlgEntries.ShowDialog() == DialogResult.OK)
					{
                        SaveFormResponse(m_objForm, strTemplate);
					}
				}
				catch(Exception ex)
				{
					MessageBox.Show(ex.Message);
				}
			}
		}

		private void DownloadTemplates()
		{
			frmDownloadTemplates dlgDownload = new frmDownloadTemplates();
			dlgDownload.ShowDialog();

			LoadForms();
			LoadCompletedForms();
		}

		private void UploadResponses()
		{
			frmUploadTemplates dlgUpload = new frmUploadTemplates();
			dlgUpload.ShowDialog();

			LoadForms();
			LoadCompletedForms();
		}

		private void Options()
		{
			frmOptions dlgOptions = new frmOptions();
			dlgOptions.ShowDialog();

			LoadForms();
			LoadCompletedForms();
		}

		private void m_objFormsMenu_ViewClicked(object sender, EventArgs e)
		{
			FillOutForm();
		}

		private void m_objFormsMenu_DeleteClicked(object sender, EventArgs e)
		{
			string strFile = String.Empty;
			string strSelection = String.Empty;
			string strFormName = String.Empty;

			strSelection = m_objFormsMenu.SelectedOption;
			// walk through the template array and find the selected item
			for(int nIndex = 0; nIndex < m_arrForms.Length; nIndex++)
			{
				strFile = m_arrForms[nIndex];
				strFormName = Path.GetFileNameWithoutExtension(strFile);
				if(strFormName == strSelection)
				{
					break;
				}
				else
				{
					strFile = String.Empty;
					strFormName = String.Empty;
				}
			}

			if(strFile != String.Empty)
			{
				try
				{
					File.Delete(strFile);
				}
				catch(Exception ex)
				{
					MessageBox.Show(ex.Message, "UIProcess");
				}
			}

			LoadForms();
		}

		private void m_objCompletedFormsMenu_ViewClicked(object sender, EventArgs e)
		{
			ReviewCompletedForm();
		}

		private void m_objCompletedFormsMenu_DeleteClicked(object sender, EventArgs e)
		{
			string strFile = String.Empty;
			string strSelection = String.Empty;
			string strFormName = String.Empty;

			strSelection = m_objCompletedFormsMenu.SelectedOption;
			// walk through the template array and find the selected item
			for(int nIndex = 0; nIndex < m_arrCompletedForms.Length; nIndex++)
			{
				strFile = m_arrCompletedForms[nIndex];
				strFormName = Path.GetFileNameWithoutExtension(strFile);
				if(strFormName == strSelection)
				{
					break;
				}
				else
				{
					strFile = String.Empty;
				}
			}

			if(strFile != String.Empty)
			{
				try
				{
					File.Delete(strFile);
				}
				catch(Exception ex)
				{
					MessageBox.Show(ex.Message, "UIProcess");
				}
			}
		
			LoadCompletedForms();
		}

        public static MobileClient.UIProcessService.Form LoadFormTemplate(string strFileName)
        {
            // Declare an object variable of the type to be deserialized.
            MobileClient.UIProcessService.Form theForm = new MobileClient.UIProcessService.Form();

            try
            {
                if (File.Exists(strFileName))
                {
                    // Create an instance of the XmlSerializer class;
                    // specify the type of object to be deserialized.
                    XmlSerializer serializer = new XmlSerializer(theForm.GetType());
                    // To read the file, create a FileStream.
                    FileStream myFileStream = new FileStream(strFileName, FileMode.Open);
                    // Call the Deserialize method and cast to the object type.
                    theForm = (MobileClient.UIProcessService.Form)serializer.Deserialize(myFileStream);
                    myFileStream.Close();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            return theForm;
        }

        public void SaveFormTemplate(MobileClient.UIProcessService.Form theForm, string strFileName)
        {
            try
            {
                // Create an instance of the XmlSerializer class;
                // specify the type of object to serialize.
                XmlSerializer serializer =
                new XmlSerializer(theForm.GetType());
                TextWriter writer = new StreamWriter(strFileName);
                // Serialize the Form, and close the TextWriter.
                serializer.Serialize(writer, theForm);
                writer.Close();

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }

        public void SaveFormResponse(MobileClient.UIProcessService.Form theForm, string strFileName)
        {
            if (theForm.FormAction.ActionType == ActionType.SaveToDisk)
            {
                StringBuilder strFilePath = new StringBuilder();
                strFilePath.Append(SettingValues.GetResponsePath());
                strFilePath.Append("\\");
                strFilePath.Append(theForm.Name);
                strFilePath.Append("_");
                strFilePath.Append(SettingValues.GetUserId());
                strFilePath.Append("_");
                strFilePath.Append(DateTime.Now.Year.ToString("0000"));
                strFilePath.Append(DateTime.Now.Month.ToString("00"));
                strFilePath.Append(DateTime.Now.Day.ToString("00"));
                strFilePath.Append("_");
                strFilePath.Append(DateTime.Now.Hour.ToString("00"));
                strFilePath.Append(DateTime.Now.Minute.ToString("00"));
                strFilePath.Append(".xml");
                SaveFormResponse(theForm, strFilePath.ToString());
            }

            if (theForm.FormAction.ActionType == ActionType.SendToWebService)
            {
                frmUploadForm theDialog = new frmUploadForm();
                theDialog.Show();
                m_objForm = theDialog.UploadForm(theForm);
            }

            if (theForm.FormAction.ActionType == ActionType.LoadNewForm)
            {
                StringBuilder strFilePath = new StringBuilder();
                strFilePath.Append(SettingValues.GetTemplatePath());
                strFilePath.Append("\\");
                strFilePath.Append(theForm.FormAction.Endpoint);
                m_objForm = LoadFormTemplate(strFilePath.ToString());
            }
        }
    }
}
